<?php

//define('PATH', "/var/www/fec/drupal-7.0/modules/");
//define('PATH', "./");
define('PATH', dirname(__FILE__).DIRECTORY_SEPARATOR);

//define('FRAMS_PROG', "../fec_bin/frams -Q -e -s -i../fec_bin/cliutils.ini makef0 -q ");
define('FRAMS_PROG', PATH."fec_bin/frams -Q -e -s -i".PATH."fec_bin/cliutils.ini makef0 -q ");
define('FRAMS_PROG_HTML', PATH."fec_bin/frams -Q -e -s -i".PATH."fec_bin/cliutils.ini htmlize -q ");
define('FRAMS_PROG_HTML_SHORT', PATH."fec_bin/frams -Q -e -s -i".PATH."fec_bin/cliutils.ini htmlizeShort -q ");
define('FRAMS_PROG_PJNC', PATH."fec_bin/frams -Q -e -s -i".PATH."fec_bin/cliutils.ini pjnc -q ");

function genotype_form($form, &$form_state) {
	$form['name'] = array(
	  '#type' => 'textfield',
	  '#title' => t('Creature name'),
	);
	
	$form['geno'] = array(
	  '#type' => 'textarea',
	  '#title' => t('Genotype'),
	);
	
	$form['origin'] = array(
	  '#type' => 'select',
	  '#title' => t('Origin'),
	  '#options' => array(
	    1 => t('Designed'),
	    2 => t('Designed and evolved'),
	    3 => t('Evolved under variuos conditions'),
	    4 => t('Evolved using single, constant setup'),
	  ),
	
	);

    $query = db_select('gene_pool', 'g');
    $pools = $query
        ->fields('g', array('id', 'name'))
        ->execute();

	$pools_form = array();
	while ($pool = $pools->fetchAssoc())
	{
		$pools_form[$pool['id']] = $pool['name'];
	}

	$form['pool_id'] = array(
	  '#type' => 'select',
	  '#title' => t('Pool'),
	  '#options' => $pools_form
	);
	
	$form['shortinfo'] = array(
	  '#type' => 'textarea',
	  '#title' => t('Short description (optional)'),
	);
	
	$form['originstory'] = array(
	  '#type' => 'textarea',
	  '#title' => t('How it was crated (optional)'),
	);
	
	$form['notes'] = array(
	  '#type' => 'textarea',
	  '#title' => t('Notes on its performance (optional)'),
	);
	
	$form['submit'] = array(
	  '#type' => 'submit',
	  '#value' => t('Submit your information'),
	);

return $form;
}

function commandResults($command)
// zwraca wynik dzialania (na stdout) programu podanego jako parametr
{
	$result = "";
    $pd = popen($command, "r") or die("Cannot execute a program.");
    while (!feof($pd))
    {   
        $result .= fgets($pd, 100);
    }   

    	pclose($pd);
    return $result;
}

function processGenotype($geno)
// funkcja sprawdzajaca poprawnosc podanego genotypu oraz obliczajaca jego reprezentacje
// w postaci f0, reprezentacje HTML, skrocona reprezentacje HTML i ilosc neuronow,
// partow, joinow i polaczen. Sa one zwracane w odpowiednich zmiennych. Jesli genotyp
// jest bledny, funkcja zakonczy dzialanie biezacego skryptu i wypisze komunikat o
// bledzie. 
{
    // stworzenie tymczasowego pliku z genotypem
    $fileName = tempnam("/tmp/", "FEC_PHP_");
    $fd = fopen($fileName, "w") or die("Cannot create a temporary file.");
	chmod($fileName, 0766);
    fputs($fd, $geno);
    fclose($fd);

    // wyznaczanie reprezentacji f0 genotypu (i zarazem sprawdzanie jego poprawnosci)
    $res["geno_F0"] = commandResults(FRAMS_PROG . " < " . $fileName);
    if (strcmp($res["geno_F0"], '') == 0)
    {
        unlink($fileName);
	return NULL;
        //die("<br/>Invalid genotype.");
    }

    // wyznaczanie HTML-owej reprezentacji genotypu
    $res["geno_html"] = commandResults(FRAMS_PROG_HTML . "< " . $fileName);

    // wyznaczanie skroconej HTML-owej reprezentacji genotypu
    $res["geno_html_short"] = commandResults(FRAMS_PROG_HTML_SHORT . "< " . $fileName);

    // wyznaczenie rozmiaru genotypu
    $pjnc = commandResults(FRAMS_PROG_PJNC . "< " . $fileName);
    $pjncTab = explode(" ", $pjnc);
    $res["count_p"] = $pjncTab[0];
    $res["count_j"] = $pjncTab[1];
    $res["count_n"] = $pjncTab[2];
    $res["count_c"] = $pjncTab[3];
    
    // usuniecie tymczasowego pliku z genotypem
    unlink($fileName);

	return $res;
}  

function genotype_form_submit($form, &$form_state)
{
	global $user;

	if (!user_is_logged_in() || !user_access('Create genotype'))
	{
		drupal_set_message(t('You cannot add creature.<br/>You have log in first.'), 'error');
		return;
	}

//	var_dump($user);
	$res = processGenotype($form["geno"]["#value"]);
	if (is_null($res))
		drupal_set_message(t('Invalid genotype.'), 'error');	
	else{
		$vals = $form_state['values'];
		var_dump($vals);
		if ($vals['pool_id'] == "")
		{
			drupal_set_message(t('You cannot add creature. <br/>None pool is created.'), 'error');
	                return;
		}
		$to_insert = array(
			'us_id' => $user->uid,
			'pool_id' => $vals['pool_id'],
			'date' => time(),
			'name' => $vals['name'],
			'shortinfo' => $vals['shortinfo'],
			'origin' => $vals['origin'],
			'originstory' => $vals['originstory'],
			'notes' => $vals['notes'],
			'geno' => $vals['geno'],
			'geno_html' => $res['geno_html'],
			'geno_html_short' => $res['geno_html_short'],
			'geno_F0' => $res['geno_F0'],
			'count_p' => $res['count_p'],
			'count_j' => $res['count_j'],
			'count_n' => $res['count_n'],
			'count_c' => $res['count_c'],
		);
		drupal_set_message(t('Submitting values: @values', array('@values' => var_export($form_state['values'], TRUE))));
		db_insert('genotypes')->fields($to_insert)->execute();	
	}
}

